package com.yfuxdeer.youchat.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yfuxdeer.youchat.R;
import com.yfuxdeer.youchat.adapter.MessageInfoListAdapter;
import com.yfuxdeer.youchat.client.Client;
import com.yfuxdeer.youchat.pojo.FriendItem;
import com.yfuxdeer.youchat.pojo.Message;
import com.yfuxdeer.youchat.pojo.User;
import com.yfuxdeer.youchat.service.FriendService;
import com.yfuxdeer.youchat.service.MessageService;
import com.yfuxdeer.youchat.utils.Store;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ChatActivity extends AppCompatActivity {

    private static final String TAG = ChatActivity.class.getSimpleName();
    private TextView nickName;
    private ListView listView;
    private List<Message> messageList;
    private User currentUser;
    private Button back;
    private Button sendBtn;
    private Button friend_info;
    private EditText msg;
    public static Handler handler;
    private Store store = Store.getInstance();
    private MessageInfoListAdapter adapter;
    private String friend_id = "";


    static {
        handler = new Handler();
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        //注册广播
        registerReceiver(findMessageReceiver, new IntentFilter("com.yfuxdeer.youchat.findMessageReceiver"));
        registerReceiver(notifyMessageReceiver, new IntentFilter("com.yfuxdeer.youchat.notifyMessageReceiver"));

        findViews();
        setListeners();
        init();
    }

    private void setListeners() {
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = msg.getText().toString();
                msg.setText("");
                if (message.equals("")) {
                    Toast.makeText(getApplicationContext(), "无内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.e(TAG, "friend_id = " + friend_id);
                Message msg = new Message(store.getCurrentUser().getUsername(), friend_id, message, new Date());

                if (store.getClient() == null) {
                    Toast.makeText(getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    store.getClient().send(msg);
                }

                if (messageList == null) return;
                messageList.add(msg);
                adapter.notifyDataSetChanged();


                //通过广播进行更新
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FriendItem friendItem = null;
                        try {
                            friendItem = FriendService.findFriendById(msg.getFrom(), msg.getTo());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Intent intent = new Intent("com.yfuxdeer.youchat.iSendMessageReceiver");
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("message", msg);
                        bundle.putSerializable("friendItem", friendItem);
                        intent.putExtras(bundle);
                        ChatActivity.this.sendBroadcast(intent);
                    }
                }).start();
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        friend_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), UserinfoActivity.class);
                intent.putExtra("user_id", friend_id);
                intent.putExtra("remark", nickName.getText());
                startActivity(intent);
            }
        });
    }

    private void findViews() {
        nickName = findViewById(R.id.nickName);
        listView = findViewById(R.id.list);
        sendBtn = findViewById(R.id.send);
        msg = findViewById(R.id.msg);
        back = findViewById(R.id.back);
        friend_info = findViewById(R.id.friend_info);
    }

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            nickName.setText(intent.getCharSequenceExtra("nickName"));
            friend_id = intent.getStringExtra("friend_id");
        }
        currentUser = Store.getInstance().getCurrentUser();

        //调用服务查询聊天记录
        intent = new Intent(getApplicationContext(), MessageService.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("method", MessageService.METHOD.FIND_MESSAGE);
        bundle.putString("host_id", currentUser.getUsername());
        bundle.putString("friend_id", friend_id);
        intent.putExtras(bundle);
        startService(intent);

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public String getFriend_id() {
        return friend_id;
    }

    private BroadcastReceiver findMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            MessageService.RESULT result = (MessageService.RESULT) bundle.getSerializable("result");
            switch (result) {
                case SUCCESS:
                    messageList = (List<Message>) bundle.getSerializable("messages");
                    if (messageList == null) {
                        messageList = new ArrayList<>();
                    }
                    adapter = new MessageInfoListAdapter(messageList, getApplicationContext(), currentUser);
                    listView.setAdapter(adapter);
                    break;
                case NETWORK_EXCEPTION:
                    Toast.makeText(getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private BroadcastReceiver notifyMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            Message message = (Message) bundle.getSerializable("message");
            Log.e(TAG, "onReceive: message = " + message);
            messageList.add(message);
            adapter.notifyDataSetChanged();
        }
    };
}